package flc.ast.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.PlayActivity;
import flc.ast.adapter.SelVideoAdapter;
import flc.ast.adapter.SelVideoAdapter1;
import flc.ast.databinding.FragmentLocalVideoBinding;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.dialog.StyleDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LocalVideoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LocalVideoFragment extends BaseNoModelFragment<FragmentLocalVideoBinding> {

    private SelVideoAdapter videoAdapter;
    private SelVideoAdapter1 videoAdapter1;
    private List<SelectMediaEntity> listShow = new ArrayList<>();
    private List<SelectMediaEntity> listDelete = new ArrayList<>();
    private StyleDialog mStyleDialog;
    private boolean hasLineStyle = true;


    @Override
    protected int onCreate() {
        return R.layout.fragment_local_video;
    }

    @Override
    protected void initView() {
        mDataBinding.llVideoNoPermission.setOnClickListener(this);

        mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext));
        videoAdapter = new SelVideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivSelVideoItemEdit);
        videoAdapter.setOnItemChildClickListener(this);
        videoAdapter.setOnItemClickListener(this);

        videoAdapter1 = new SelVideoAdapter1();
        videoAdapter1.addChildClickViewIds(R.id.ivSelVideoItemEdit);
        videoAdapter1.setOnItemChildClickListener(this);
        videoAdapter1.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llVideoNoPermission://申请权限
                getPermission();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PlayActivity.listPlay = listShow;
        PlayActivity.type = 0;
        PlayActivity.selPlayPos = position;
        startActivity(PlayActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivSelVideoItemEdit://编辑
                showEditDialog(position);
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (StkPermissionHelper.hasGrantManageExternalStoragePermission(mContext)) {
            getData();
            mDataBinding.llVideoNoPermission.setVisibility(View.GONE);
        } else {
            mDataBinding.llVideoNoPermission.setVisibility(View.VISIBLE);
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.tvVideoNoData.setVisibility(View.GONE);
        }
    }

    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_video_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                        mDataBinding.llVideoNoPermission.setVisibility(View.GONE);
                    }
                }).request();
    }

    //获取视频和图片数据
    private void getData() {
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    listShow.addAll(selectMediaEntities);
                    videoAdapter.setList(selectMediaEntities);
                    videoAdapter1.setList(selectMediaEntities);
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                    mDataBinding.tvVideoNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvVideoList.setVisibility(View.GONE);
                    mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void showRankDialog() {
        if (mStyleDialog == null) {
            mStyleDialog = new StyleDialog(mContext);
        }
        mStyleDialog.setListener(new StyleDialog.Ilistener() {
            @Override
            public void clickListLayout() {
                hasLineStyle = true;
                mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext));
                mDataBinding.rvVideoList.setAdapter(videoAdapter);

            }

            @Override
            public void clickGridLayout() {
                hasLineStyle = false;
                mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 2));
                mDataBinding.rvVideoList.setAdapter(videoAdapter1);

            }

            @Override
            public void rankToTime() {
                sortFileBeanList(1);
            }

            @Override
            public void rankToTitle() {
                sortFileBeanList(2);

            }

            @Override
            public void rankToDuration() {
                sortFileBeanList(3);

            }

            @Override
            public void rankToSize() {
                sortFileBeanList(4);
            }
        });
        mStyleDialog.show();
    }

    public void sortFileBeanList(int sortBy) {
        switch (sortBy) {
            case 1:
                // 按时间排序
                Collections.sort(listShow, new Comparator<SelectMediaEntity>() {
                    @Override
                    public int compare(SelectMediaEntity o1, SelectMediaEntity o2) {
                        Date date1 = null;
                        Date date2 = null;
                        date1 = new Date(FileUtils.getFileLastModified(o1.getPath()));
                        date2 = new Date(FileUtils.getFileLastModified(o2.getPath()));
                        return date1.compareTo(date2);
                    }
                });
                break;
            case 2:
                // 按标题排序
                Collections.sort(listShow, new Comparator<SelectMediaEntity>() {
                    @Override
                    public int compare(SelectMediaEntity o1, SelectMediaEntity o2) {
                        return o1.getMediaName().compareTo(o2.getMediaName());
                    }
                });
                break;
            case 3:
                // 按时长排序
                Collections.sort(listShow, new Comparator<SelectMediaEntity>() {
                    @Override
                    public int compare(SelectMediaEntity o1, SelectMediaEntity o2) {
                        return Long.compare(o1.getDuration(), o2.getDuration());
                    }
                });
                break;
            case 4:
                // 按大小排序
                Collections.sort(listShow, new Comparator<SelectMediaEntity>() {
                    @Override
                    public int compare(SelectMediaEntity o1, SelectMediaEntity o2) {
                        long length1 = new File(o1.getPath()).length();
                        long length2 = new File(o2.getPath()).length();
                        return Long.compare(length1, length2);
                    }
                });
                break;
            default:
                break;
        }
        videoAdapter.setList(listShow);
        videoAdapter1.setList(listShow);
    }

    public boolean getHasLineStyle() {
        return hasLineStyle;
    }

    private void showEditDialog(int position) {
        EditDialog dialog = new EditDialog(mContext);
        dialog.selectMediaEntity = listShow.get(position);
        dialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickRename() {
                showRenameDialog(position);
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listShow.get(position).getPath());
            }

            @Override
            public void clickAddPrivacyFolder() {
                String filePath = FileUtil.generateFilePath(Content.myPrivacyVideo, "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
                FileUtils.copy(listShow.get(position).getPath(), filePath);
                ToastUtils.showShort(getString(R.string.add_suc));
            }

            @Override
            public void clickInfo() {
                showInfoDialog(position);
            }

            @Override
            public void clickDelete() {
                getDeletePermission(position);
            }
        });
        dialog.show();
    }

    private void showRenameDialog(int position) {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.title = getString(R.string.file_rename);
        dialog.hint = getString(R.string.please_input_folder_name_text);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listShow.get(position).getPath(), name + "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
                getData();
            }
        });
        dialog.show();
    }

    //获取权限
    private void getDeletePermission(int position) {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_all_storage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        delete(position);
                    }
                })
                .request();
    }

    private void delete(int position) {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        mContext.getContentResolver().delete(Uri.parse(listShow.get(position).getUri()), null, null);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        listDelete.clear();
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void showInfoDialog(int position) {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listShow.get(position).getPath();
        dialog.show();
    }

}